# coding: utf-8
from collections import deque

from PySide6.QtCore import QThread, Signal


class WorkerThread(QThread):
    failed = Signal(str)
    result = Signal(object, object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.queue = deque()

    def run(self):
        while self.queue:
            func, args, kwargs, slot = self.queue.popleft()
            try:
                result = func(*args, **kwargs)
                self.result.emit(slot, result)
            except Exception as e:
                self.failed.emit(str(e))

    def addTask(self, func, *args, slot=None, **kwargs):
        self.queue.append((func, args, kwargs, slot))
        if not self.isRunning():
            self.start()
